package com.zhjw.controller;

import com.zhjw.common.response.ResponseResult;
import com.zhjw.entity.ExternalUser;
import com.zhjw.entity.MasterUser;
import com.zhjw.service.ExternalUserService;
import com.zhjw.service.MasterUserService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;

/**
 * Created by zhjw on 2023/3/6
 * <p>
 *
 * </p>
 *
 * @author zhjw
 * @date 2023/3/6
 */
@RestController
@RequestMapping("/insert")
public class TestController {

    @Resource
    private MasterUserService masterUserService;

    @Resource
    private ExternalUserService externalUserService;

    @RequestMapping(value = "/master", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
    public ResponseResult master() {
        MasterUser masterUser = new MasterUser();
        masterUser.setId(System.currentTimeMillis());
        masterUser.setName("张");
        masterUserService.insert(masterUser);
        return ResponseResult.success();
    }

    @RequestMapping(value = "/external", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
    public ResponseResult external() {
        ExternalUser externalUser = new ExternalUser();
        externalUser.setId(System.currentTimeMillis());
        externalUser.setName("李");
        externalUserService.insert(externalUser);
        return ResponseResult.success();
    }

    /**
     * 基于Service事务插入的接口
     *
     * @return
     */
    @RequestMapping(value = "/union", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
    public ResponseResult union() {
        MasterUser masterUser = new MasterUser();
        masterUser.setId(System.currentTimeMillis());
        masterUser.setName("张");
        masterUserService.insert(masterUser);

        ExternalUser externalUser = new ExternalUser();
        externalUser.setId(System.currentTimeMillis());
        externalUser.setName("李");
        externalUserService.insert(externalUser);
        return ResponseResult.success();
    }


    /**
     * 基于Controller事务插入的接口
     *
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @RequestMapping(value = "/unionTransactional", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
    public ResponseResult unionTransactional() {
        MasterUser masterUser = new MasterUser();
        masterUser.setId(System.currentTimeMillis());
        masterUser.setName("张");
        masterUserService.insert(masterUser);

        ExternalUser externalUser = new ExternalUser();
        externalUser.setId(System.currentTimeMillis());
        externalUser.setName("李");
        externalUserService.unionTransactional(externalUser);
        return ResponseResult.success();
    }

}
